/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-02-03 14:47:36
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 15:57:18
 */

'use strict';
/*
 *   路由管理
 *   监听hashchange，load页面
 * */
define([
    '../framework/pieces/footer',
    '../../modules/common/checkuser'
], function(
    footer,
    checkuser
    ) {
    var HashManager = {
        init: function() {
            var _this = this;
            $('script').attr('hash-change-before', 'true');
            _this.bindHashChangeEvent();
            _this.parseRoute();
        },
        /*
         *   路由基础路径
         * */
        basePath: undefined,
        /*
         *   hash被解析次数
         * */
        changeNumber: 0,
        /*
         *   最大解析次数，超过次数将进行刷新，强制清理内存
         * */
        maxChangeNumber: 30,
        /*
         *绑定hashchange事件
         * */
        bindHashChangeEvent: function() {
            var _this = this;
            $(window).unbind('hashchange');
            $(window).bind('hashchange', function(e) {
                if (_this.changeNumber >= _this.maxChangeNumber) {
                    window.location.reload();
                    _this.changeNumber = 0;
                } else {
                    _this.parseRoute();
                }
                _this.changeNumber++;
            });
        },
        defaultPage: function() {
            var roleId = window.sessionStorage.getItem('roleIds');
            if (!roleId) {
                window.location.hash = '#!login';
                return;
            }

            if (roleId.indexOf(1) != -1) {
                //管理员 !createAd
                window.location.hash = '#!createAd';
            } else if (roleId.indexOf(2) != -1 || roleId.indexOf(4) != -1) {
                //投放者
                window.location.hash = '#!createAd';
            } else if (roleId.indexOf(3) != -1 || roleId.indexOf(6) != -1) {
                //设计者
                window.location.hash = '#!imageManage';
            } else {
                console.log("未知角色");
            }
        },
        /*
         * 解析路由
         * */
        parseRoute: function() {
            var _this = this;
            var _hash = window.location.hash,
                _pathname = window.location.pathname;
            if (_hash.indexOf('?') > 0) {
                _hash = _hash.substr(0, _hash.indexOf('?'));
            }
            if (_hash == '' || /[#!\/]$/.test(_hash)) {
                _this.defaultPage();
                return;
            }
            $("[data-seg='menu']").find('.list-item.list-leaf.active').removeClass('active');
            if (_hash == '#!lookalikeAudience') {
                $("[data-seg='menu']").find('a[href="#!customAudience"]').closest('.list-item.list-leaf').addClass('active');
            } else {
                $("[data-seg='menu']").find('a[href="' + _hash + '"]').closest('.list-item.list-leaf').addClass('active');
            }

            if ($('.with-full-sidepanel-panel')[0]) {
                $('.with-full-sidepanel-panel').remove();
                $('.sidepanel-backdrop').remove();
            }

            checkuser.checkUser(function(_pathNameParam) {
                if (_pathNameParam) {
                    window.pageName = _pathNameParam;
                    _this.loadPage(_pathNameParam);
                } else {
                    //预处理url
                    _pathname == '/' ? _pathname = '' : '';
                    var _pathnameArray = _pathname.split('/'),
                        pageName = _hash.split('#!')[1];
                    if (typeof(_this.basePath) == 'undefined') {
                        _this.basePath = _pathname.indexOf('.html') == -1 ? _pathname : _pathnameArray.slice(0, _pathnameArray.length - 1).join('/');
                    }
                    window.pageName = pageName;
                    _this.loadPage(pageName);
                }
            });
        },
        /*
         * 加载页面
         * */
        loadPage: function(pageName) {
            var _this = this;
            //加载页面
            var warp = $('#layout-main'),
                nav = $('#layout-aside');
            if (!warp || warp.length == 0) {
                console.error('hashManager.parseRoute():', '未能找到有效的外围元素');
                return;
            }

            console.info(window.parent);
            warp.addClass('loading-page');
            var htmlUrl = '',
                jsUrl = '';
            var vpath = '';
            if (cors_config.isTest) {
                htmlUrl = './' + pageName + '.html';
                jsUrl = '../src/js/' + pageName + '.js';
            } else {
                // if (window.fmpversion.length > 0) {
                //     vpath = './' + window.fmpversion;
                // } else {
                //     vpath = '.';
                // }
                vpath = '.';
                htmlUrl = vpath + '/' + pageName + '.html';
                jsUrl = vpath + '/js/' + pageName + '.js';
            }
            //移除在index方法后加载script节点
            try {
                var hashChangeAfterScript = $('script[hash-change-before!="true"]');
                if (hashChangeAfterScript.length > 0) {
                    hashChangeAfterScript.remove();
                }
            } catch (e) {
                console.log("忽略这个错误!")
                console.error(e)
            }
            window.top.location.hash = window.location.hash; //改变top的hash
            $.ajax({
                url: htmlUrl,
                type: 'GET'
            }).done(function(tpl) {
                var t = tpl;
                if (!cors_config.isTest) {
                    t = tpl.replace(/href=\"\.\/css\/pages\//, 'href="' + vpath + '/css/pages/' + pageName + '.css"')
                }
                $('.fmp-article').scrollTop(0); //滚动到顶部
                warp.empty().html(I18N.parse(t, window.pageName));
                _this.loadJs(jsUrl, pageName);
            }).fail(function(error) {
                if (error.status == 404) {
                    console.info('not found! load current path!')
                    htmlUrl = './' + pageName + '.html';
                    jsUrl = './js/' + pageName + '.js';
                    $.get(htmlUrl, function(tpl) {
                        $('.fmp-article').scrollTop(0); //滚动到顶部
                        warp.empty().html(I18N.parse(tpl, window.pageName));
                        _this.loadJs(jsUrl);
                    }).fail(function() {
                        _this.defaultPage();
                    });
                }
            }).always(function() {});
        },
        loadJs: function(jsurl, pageName) {
            //加载javascript
            require(['./' + jsurl], function() {
                var warp = $('#layout-main');
                var nav = $("[data-seg='menu']");
                console.log('there are hashManager.js');
                var curObj = window[window.pageName];
                if (typeof(curObj) != 'undefined') {
                    if (curObj.startup) {
                        curObj.startup()
                    } else {
                        curObj.init()
                    }
                } else {
                    console.warn('该页面不存在含init方法的角本,直接跳过');
                }
                jQuery = $ = window.j$;
                $('.active', nav).removeClass('active');
                // 自定义受众专属调转
                if (pageName == 'lookalikeAudience') {
                    pageName = 'customAudience';
                }

                if (pageName == 'adOptimize'){
                    pageName = 'adMarketTarget';
                }
                $('a[href="#!' + pageName + '"]', nav).closest('li').addClass('active');
                footer.init();
                warp.removeClass('loading-page');
            });
        }

    }
    return HashManager;
});
